/* eslint-disable prefer-promise-reject-errors */
import store from '../index'
import { resetRouter } from '@router/index'
import Utils from '@utils/index'
import MyServer from '@api/index.js'

const getDefaultState = () => {
  return {
    token: Utils.token.get(),
    userInfo: Utils.localStorage.get('userInfo') || {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => { // 重置state数据
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      MyServer.user
        .login({
          data: userInfo,
          method: 'post'
        })
        .then(res => {
          const { loginSysUserVo, token } = res
          commit('SET_TOKEN', token)
          Utils.token.set(token)
          Utils.localStorage.set('userInfo', loginSysUserVo)
          commit('SET_USERINFO', loginSysUserVo)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      store.dispatch('permission/resetNewRoutes')
      store.dispatch('settings/clearTheme')
      store.dispatch('tagsView/delAllViews')
      commit('RESET_STATE')
      commit('SET_TOKEN', '')
      resetRouter()
      Utils.sessionStorage.clear()
      Utils.localStorage.clear()
      Utils.token.remove()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
